package sort.bubble;

import java.util.Arrays;

public class BubbleSorted {

    public static int[] bubbleSolution01(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return arr;
        }
        int length = arr.length;

        //外部循环没进行一次，都会确定一个元素的最终位置，所以只需要判断length-1次即可
        for (int j = length; j > 0; j--) {
            for (int i = 0; i < j - 1; i++) {
                if (arr[i] > arr[i+1]) {
                    //交换时的第一步，为temp = arr[i];那么第二步为的等号左边为arr[i]等号右边为arr[i+1]
                    int temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                }
            }
        }
        return arr;
    }

    public static int[] bubbleSolution02(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return arr;
        }
        int length = arr.length;
        boolean flag = false;

        for (int j = length; j > 0; j--) {
            for (int i = 0; i < j - 1; i++) {
                if (arr[i] > arr[i+1]) {
                    //交换时的第一步，为temp = arr[i];那么第二步为的等号左边为arr[i]等号右边为arr[i+1]
                    int temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                }
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {10, 6, 4, 7, 9, 20, 14};
        int[] solution01 = bubbleSolution01(arr);
        System.out.println(Arrays.toString(solution01));
    }
}
